package handler

import (
	"gmfs/core/logger"
	"gmfs/core/storage"
	"gmfs/core/web/ink"
	"gmfs/core/web/model"
	"gopkg.in/mgo.v2"
	"io"
	"strconv"
	"strings"
)

/**
 * 图片展示,文件下载
 * http://localhost:1323/dispaly/xxx
 */
func Dispaly(ctx *ink.Context) {
	var ic = "" //图片处理参数，例如 100x100
	id := ctx.Param("id")

	if strings.Contains(id, "_") {
		ix := strings.Split(id, "_")
		id = ix[0]
		ic = ix[1]
		logger.Debugf("Dispaly id:%s, ic:%s", id, ic)
	}

	//查询 gridfs
	ii, gf, err := storage.FindInfoById(Connection, id)
	if err != nil || !allowReq(ctx) {
		ctx.Body = []byte("not found")
		ctx.End()
		return
	} else {
		//存在文件
		defer gf.Close()
		if ii != nil {
			if ii.GetFileType() == 0 {
				//图片文件
				b, w, h := icHandle(gf, ic)
				if ii.GetContentType() == "image/gif" {
					io.Copy(ctx.Response, storage.ResizeGif(ctx, gf, b, w, h))
				} else {
					io.Copy(ctx.Response, storage.ResizeImage(ctx, gf, b, w, h))
				}
			} else {
				//二进制文件
				io.Copy(ctx.Response, gf)
			}
		}
	}

	ctx.IsSend = true
}

/**
 * 文件上传
 * http://localhost:1323/search/file-md5-value/file-size-value
 * 例如：http://localhost:1323/search/f430fb99420b8ddf584284744fba3ba5/15954
 */
func Search(ctx *ink.Context) {
	fileMd5 := ctx.Param("md5")
	fileSize, err := strconv.Atoi(ctx.Param("size"))
	if err != nil {
		logger.Errorln(err)
		JsonInfo(ctx, model.MSG_ERROR, "", "", "", err.Error())
		return
	}

	inf, err := storage.SearchExist(Connection, fileMd5, fileSize)
	if err != nil {
		logger.Errorln(err)
		JsonInfo(ctx, model.MSG_ERROR, "", "", "", err.Error())
		return
	}

	JsonInfo(ctx, model.MSG_SUCCESS, inf.GetContentType(), inf.GetFileSuffix(),
		inf.GetRdm(), inf.GetIdToString())
	return
}

/**
 * 图片参数 ic
 * 判断处理
 */
func icHandle(gf *mgo.GridFile, ic string) (bool, uint, uint) {
	var im *model.ImgMeta
	err := gf.GetMeta(&im)
	if err != nil {
		//图片元信息异常
		logger.Errorln(err)
	} else {
		//处理传入参数
		if strings.Contains(ic, "x") {
			icArr := strings.Split(ic, "x")
			w, err := strconv.Atoi(icArr[0])
			if err != nil {
				return false, 0, 0
			}

			h, err := strconv.Atoi(icArr[1])
			if err != nil {
				return false, 0, 0
			}

			//限制宽高大于 50 像素, 宽高小于2倍的实际像素
			if w >= 50 && w <= 2*im.GetWidth() && h >= 50 && h <= 2*im.GetHeight() {
				return true, uint(w), uint(h)
			}
		} else {
			//等比缩放
			w, err := strconv.Atoi(ic)
			if err != nil {
				return false, 0, 0
			}
			if w >= 50 && w <= 2*im.GetWidth() {
				return true, uint(w), 0
			}
		}
	}
	return false, 0, 0
}
